﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DBBase;

using System.Threading;

using System.IO;

using System.Web;
using System.Runtime.InteropServices;
using System.IO.Ports;
using System.Security;
using System.Security.Cryptography;

using System.Diagnostics;

using System.Net.Sockets;
using System.Net;




namespace Business
{
    public partial class userlogin : DevExpress.XtraEditors.XtraForm
    {
        public userlogin()
        {
            InitializeComponent();
            idlsbcsxz = 5;
            sjieshou = "";
            connet();
        }

        public int idlsbcsxz;
        public int idlsbcsxzzd;//终端
        public bool  bjieshou;
        public string sjieshou;
        public string syhjs="";
        public int izxrsyq;
        public int izxrs;
        public string sip;
        public int iyfzfwcs;
        public int itqtsts;
        public string sname;
        public string YHLB;//登录的人员名称
        public bool check()
        {
            
            if (com_yonghu.Text == "")
            {
                MessageBox.Show("用户名不能为空");
                return false;
            }
            //if (t_mima.Text.Length < 8 || t_mima.Text.Length > 20)
            //{
            //    MessageBox.Show("密码长度必须为8~20位");
            //    return false;
            //}
            string s =
                        @"  
                        (?=.*[0-9])                         #必须包含数字  
                        (?=.*[a-zA-Z])                      #必须包含小写或大写字母  
                        (?=([\x21-\x7e]+)[^a-zA-Z0-9])      #必须包含特殊符号  
                        .{8,20}                             #至少8个字符，最多20个字符  
                        ";
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(s, System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace);
            if (!reg.IsMatch(t_mima.Text.Trim()))
            {
                //MessageBox.Show("密码必须至少8个字符，最多20个字符，\r\n并且至少有1个字母、\r\n至少有1个数字、\r\n至少有1个特殊字符!");
              //  return false;
            }

             bjieshou = false;
               /* string ssend = Encryption(com_yonghu.Text);
                ClientSendMsg(ssend);//发送给客户端
                for (; ; )
                {
                    if (bjieshou)
                    {
                        break;
                    }
                }

                string jieshoujieguo = "";
                if (sjieshou.Length > 0)
                {
                   jieshoujieguo= decode(sjieshou);
                }*/
               
                ///
                Query mquery = new Query();
                string sql="";
                sql = string.Format(@"Select * From USERE where YHLB='{0}' ", com_yonghu.Text);
                string sright = "111111111111";
                DataTable dt = mquery.GetTable(sql);//lzj
                if (dt.Rows.Count > 0)//lzj
                //if (jieshoujieguo.Length > 0)
                {
                    string sqzxgmm = "";
                    string suid = dt.Rows[0]["UID"].ToString().Trim();
                    YHLB = dt.Rows[0]["YHLB"].ToString().Trim();
                    sname = dt.Rows[0]["NAME"].ToString().Trim();
                    string sGZRYBH = dt.Rows[0]["GZRYBH"].ToString().Trim();
                    string smimajiami = dt.Rows[0]["PASSWORD"].ToString().Trim();
                    string sfyjdl = dt.Rows[0]["SFYJDL"].ToString().Trim();
                    string yhyxq = dt.Rows[0]["YHYXQ"].ToString().Trim();
                    string mmyxq = dt.Rows[0]["MMYXQ"].ToString().Trim();
                    string qssj = dt.Rows[0]["QSSJ"].ToString().Trim();
                    string jssj = dt.Rows[0]["JSSJ"].ToString().Trim();
                    string ip1 = dt.Rows[0]["GDIP1"].ToString().Trim();
                    string ip2 = dt.Rows[0]["GDIP2"].ToString().Trim();
                    string ip3 = dt.Rows[0]["GDIP3"].ToString().Trim();
                    string zhuangtai = dt.Rows[0]["ZT"].ToString().Trim();
                    string scdlsj = dt.Rows[0]["ZJDLSJ"].ToString().Trim();
                    syhjs = dt.Rows[0]["YHJS"].ToString().Trim();
                    
                    sqzxgmm=dt.Rows[0]["QZXGMM"].ToString().Trim();
                   /* string suid = jieshoujieguo.Split(new char[] { ',' })[0];
                    string sname = jieshoujieguo.Split(new char[] { ',' })[1];
                  
                    string sGZRYBH = jieshoujieguo.Split(new char[] { ',' })[2];
                    string smimajiami = jieshoujieguo.Split(new char[] { ',' })[3];
                    string sfyjdl = jieshoujieguo.Split(new char[] { ',' })[4];
                    string yhyxq = jieshoujieguo.Split(new char[] { ',' })[5];
                    string mmyxq = jieshoujieguo.Split(new char[] { ',' })[6];
                    string qssj = jieshoujieguo.Split(new char[] { ',' })[7];
                    string jssj = jieshoujieguo.Split(new char[] { ',' })[8];
                    string ip1 = jieshoujieguo.Split(new char[] { ',' })[9];
                    string ip2 = jieshoujieguo.Split(new char[] { ',' })[10];
                    string ip3 = jieshoujieguo.Split(new char[] { ',' })[11];
                    string zhuangtai = jieshoujieguo.Split(new char[] { ',' })[12];

                    string scdlsj = jieshoujieguo.Split(new char[] { ',' })[13];
                    syhjs = jieshoujieguo.Split(new char[] { ',' })[14];
                    sqzxgmm = jieshoujieguo.Split(new char[] { ',' })[15];
                    YHLB = com_yonghu.Text;
                   */

                   
                    
                        if (sqzxgmm.Contains("是"))//强制修改密码
                        {

                            if (zhuangtai.Contains("在用"))
                            {
                                MessageBox.Show("该用户锁定后需修改密码，请先修改密码");
                                qianzhixiugaimima m_wjxm = new qianzhixiugaimima(suid, sname, sGZRYBH, com_yonghu.Text);
                                m_wjxm.ShowDialog();

                                sql = string.Format(@" update USERE set QZXGMM=''   where YHLB='{0}' ", com_yonghu.Text);
                                mquery.InsertDB(sql);
                                return false;
                            }
                        }
                    



                   // string smimajiemi = smimajiami;  //decode(sjieshou);

                        string smimajiemi = (smimajiami);//LZJsqlldd
                        //string smimajiemi = Decrypt(smimajiami);//LZJsqlldd
                     string sdlmima = t_mima.Text;// "";
                    //sdlmima = string.Format(@"{0}{1}{2}{3}", suid, sname, sGZRYBH, t_mima.Text);
                     if (smimajiemi == sdlmima)//判断密码
                     {
                         return true;
                     }
                    if (smimajiemi == sdlmima)//判断密码
                    {
                        try
                        {
                            Query mqueryzxrs = new Query();
                            string sqlzxrs = string.Format(@"Select * From ziyuankongzhi where username='最大用户会话连接数'");
                            if (mqueryzxrs.GetDBString(sqlzxrs, "zhuangtai").Contains("开启"))
                            {
                                int.TryParse(mqueryzxrs.GetDBString(sqlzxrs, "keyzhi"), out izxrsyq);
                                if (izxrs > izxrsyq - 1)
                                {
                                    MessageBox.Show("同时在线用户超过最大会话连接数");
                                    return false;
                                }
                            }

                            DateTime dzyks;
                            DateTime dzyjs;

                            sqlzxrs = string.Format(@"Select * From ziyuankongzhi where username='特殊时间段访问'");
                            if (mqueryzxrs.GetDBString(sqlzxrs, "zhuangtai").Contains("开启"))
                            {
                                string szhi = mqueryzxrs.GetDBString(sqlzxrs, "keyzhi");
                                dzyks = Convert.ToDateTime(szhi.Split(new char[] { '~' })[0]);
                                dzyjs = Convert.ToDateTime(szhi.Split(new char[] { '~' })[1]);

                                DateTime dnow1 = Convert.ToDateTime(DateTime.Now.ToString("HH:mm:ss"));

                                if (dnow1 < dzyks || dnow1 > dzyjs)
                                {

                                    //  baocunaqrj("特殊时间段访问", com_yonghu.Text, string.Format("超出时间段{0}~{1}访问", szhi.Split(new char[] { '~' })[0], szhi.Split(new char[] { '~' })[1]));

                                    baocunaqrj("用户登录", "查询", "业务系统", "否", "否", "失败", string.Format("特殊时间段访问 超出时间段{0}~{1}访问", szhi.Split(new char[] { '~' })[0], szhi.Split(new char[] { '~' })[1]));//事件、类型（增、删、该、查）、模块、是否核心功能、是否非常规业务、结果和描述

                                    baocunaqsj("特殊时间段访问", com_yonghu.Text, string.Format("超出时间段{0}~{1}访问", szhi.Split(new char[] { '~' })[0], szhi.Split(new char[] { '~' })[1]));
                                    MessageBox.Show("账户在特殊时间段访问");
                                    return false;
                                }

                            }


                            //判断帐号是否长期未使用

                            DateTime dscdlsj = Convert.ToDateTime(scdlsj);
                            if (DateDiff(DateTime.Now, dscdlsj) > 90)
                            {

                                MessageBox.Show(string.Format("该帐号长期未使用，已经超过{0}天未使用请重新解锁", DateDiff(DateTime.Now, dscdlsj)));

                                // baocunaqrj("帐号长期未使用", com_yonghu.Text, string.Format("已经超过{0}天未使用请重新解锁", DateDiff(DateTime.Now, dscdlsj)));
                                baocunaqrj("用户登录", "查询", "业务系统", "否", "否", "失败", string.Format("帐号长期未使用 已经超过{0}天未使用请重新解锁", DateDiff(DateTime.Now, dscdlsj)));//事件、类型（增、删、该、查）、模块、是否核心功能、是否非常规业务、结果和描述

                                baocunaqsj("帐号长期未使用", com_yonghu.Text, string.Format("已经超过{0}天未使用请重新解锁", DateDiff(DateTime.Now, dscdlsj)));
                                //
                                //锁定帐号
                                sql = string.Format(@" update USERE set ZT='{0}',PASSWORD='{1}',QZXGMM='是'   where YHLB='{2}' ", "锁定", Encryption("admin_888888"), com_yonghu.Text);
                                mquery.InsertDB(sql);

                                return false;
                            }
                            // 判断账户已经登录
                            if (sfyjdl.Contains("是"))
                            {
                                baocundlrj(com_yonghu.Text, "登录系统", "其他终端登录该帐号", "失败");
                                MessageBox.Show("其他终端已登录该帐号,该终端被强制退出登录");
                                return false;
                            }
                            //判断账户是否过期 
                            DateTime dtime = Convert.ToDateTime(yhyxq);
                            if (DateTime.Now > dtime)
                            {
                                baocundlrj(com_yonghu.Text, "登录系统", "用户帐号已过期", "失败");
                                //  baocunaqrj("帐号过期访问", com_yonghu.Text, "用户帐号已过期");
                                baocunaqrj("用户登录", "查询", "业务系统", "否", "否", "失败", string.Format("帐号过期访问:用户帐号{0}已过期", com_yonghu.Text));//事件、类型（增、删、该、查）、模块、是否核心功能、是否非常规业务、结果和描述

                                baocunaqsj("帐号过期访问", com_yonghu.Text, "用户帐号已过期");
                                MessageBox.Show("用户帐号已过期 请重新激活");
                                sql = string.Format(@" update USERE set ZT='{0}',PASSWORD='{1}',QZXGMM='是'   where YHLB='{2}' ", "锁定", Encryption("admin_888888"), com_yonghu.Text);
                                mquery.InsertDB(sql);
                                return false;
                            }
                            //判断密码是否过期
                            DateTime mmdt = Convert.ToDateTime(mmyxq);
                            if (DateTime.Now > mmdt)
                            {
                                baocundlrj(com_yonghu.Text, "登录系统", "用户密码已过期", "失败");
                                //baocunaqrj("密码过期访问", com_yonghu.Text, "用户密码已过期");
                                baocunaqrj("用户登录", "查询", "业务系统", "否", "否", "失败", string.Format("密码过期访问:用户{0}密码已过期", com_yonghu.Text));//事件、类型（增、删、该、查）、模块、是否核心功能、是否非常规业务、结果和描述

                                baocunaqsj("密码过期访问", com_yonghu.Text, "用户密码已过期");
                                MessageBox.Show("用户密码已过期 请重新激活");
                                sql = string.Format(@" update USERE set ZT='{0}',PASSWORD='{1}',QZXGMM='是'   where YHLB='{2}' ", "锁定", Encryption("admin_888888"), com_yonghu.Text);
                                mquery.InsertDB(sql);
                                return false;
                            }
                            //判断规定时间段 

                            string snow = DateTime.Now.ToString("HH:mm:ss");
                            DateTime dnow = Convert.ToDateTime(snow);

                            if (dnow < Convert.ToDateTime(qssj) || dnow > Convert.ToDateTime(jssj))
                            {
                                baocundlrj(com_yonghu.Text, "登录系统", "不在允许的时间段内登录", "失败");
                                //   baocunaqrj("非正常时段访问", com_yonghu.Text, string.Format("超出时间段{0}~{1}访问", qssj, jssj));
                                baocunaqrj("用户登录", "查询", "业务系统", "否", "否", "失败", string.Format("非正常时段访问:用户{0}超出时间段{1}~{2}访问", com_yonghu.Text, qssj, jssj));//事件、类型（增、删、该、查）、模块、是否核心功能、是否非常规业务、结果和描述

                                baocunaqsj("非正常时段访问", com_yonghu.Text, string.Format("超出时间段{0}~{1}访问", qssj, jssj));
                                MessageBox.Show("不在允许的时间段内登录");
                                return false;
                            }

                            //判断不运行的IP地址内
                            string ip = string.Format(@"{0};{1};{2}", ip1, ip2, ip3);
                            if (!(ip.Contains(sip)))
                            {
                                baocundlrj(com_yonghu.Text, "登录系统", "未在规定IP范围内登录", "失败");
                                //   baocunaqrj("非规定IP范围内访问", com_yonghu.Text, "未在规定IP范围内登录");
                                baocunaqrj("用户登录", "查询", "业务系统", "否", "否", "失败", string.Format("非规定IP范围内访问:用户{0}未在规定IP范围内登录", com_yonghu.Text));//事件、类型（增、删、该、查）、模块、是否核心功能、是否非常规业务、结果和描述

                                baocunaqsj("非规定IP范围内访问", com_yonghu.Text, "未在规定IP范围内登录");
                                MessageBox.Show("未在规定IP范围内登录");
                                return false;
                            }


                            // 判断是否停用     
                            if (!(zhuangtai.Contains("在用")) && zhuangtai.Length > 0)
                            {
                                baocundlrj(com_yonghu.Text, "登录系统", zhuangtai, "失败");
                                MessageBox.Show(string.Format("该帐号状态为{0}", zhuangtai));
                                //  baocunaqrj("账户非在用状态访问", com_yonghu.Text, string.Format("该帐号状态为{0}", zhuangtai));

                                baocunaqrj("用户登录", "查询", "业务系统", "否", "否", "失败", string.Format("账户非在用状态访问:用户{0}状态为{1}", com_yonghu.Text, zhuangtai));//事件、类型（增、删、该、查）、模块、是否核心功能、是否非常规业务、结果和描述


                                baocunaqsj("账户非在用状态访问", com_yonghu.Text, string.Format("该帐号状态为{0}", zhuangtai));

                                baocunzysjrj("账户非正常状态访问", com_yonghu.Text, string.Format("该帐号状态为{0}", zhuangtai));
                                return false;
                            }

                            //判断当前时间前一分钟一共访问了多少次 提示并记录
                            string ssqlcount = string.Format(@" select * from dengluriji where dlsj>'{0}' and dlsj<'{1}' and username='{2}' ", DateTime.Now.AddMinutes(-1).ToString("yyyy-MM-dd HH:mm:ss"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), com_yonghu.Text);

                            int isqlcount = mquery.selectDBcount(ssqlcount);
                            //  MessageBox.Show(string.Format("{0}", isqlcount));
                            if (isqlcount > iyfzfwcs)
                            {
                                MessageBox.Show(string.Format("1分钟内访问次数为{0}", isqlcount));
                                // baocunaqrj("1分钟访问次数超限", com_yonghu.Text, string.Format("1分钟内访问次数为{0}", isqlcount));
                                baocunaqrj("用户登录", "查询", "业务系统", "否", "否", "失败", string.Format("1分钟访问次数超限:用户{0}在1分钟内访问次数为{1}", com_yonghu.Text, isqlcount));//事件、类型（增、删、该、查）、模块、是否核心功能、是否非常规业务、结果和描述


                                baocunaqsj("1分钟访问次数超限", com_yonghu.Text, string.Format("1分钟内访问次数为{0}", isqlcount));
                                return false;
                            }



                            if (DateDiff(DateTime.Now, mmdt) < itqtsts)//提示密码到期
                            {
                                MessageBox.Show(string.Format("{0}天后密码到期", DateDiff(DateTime.Now, mmdt)));
                            }

                            updaterenshu();
                            baocundlrj(com_yonghu.Text, "登录系统", string.Format(@"{0}用户登录成功", com_yonghu.Text), "成功");

                            dengluxinxi m_wjxm = new dengluxinxi(com_yonghu.Text, sip);
                            m_wjxm.ShowDialog();


                            sql = string.Format(@" update USERE set MMCWCS='0',SFYJDL='是',ZJDLSJ='{0}'   where YHLB='{1}' ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), com_yonghu.Text);
                            mquery.InsertDB(sql);

                        }
                        catch { }
                    }
                    else
                    {
                     //   MessageBox.Show("密码不正确");
                        //记录密码失败次数 
                        string smmcwcs = mquery.GetDBString(sql, "MMCWCS").Trim();
                        int icount = 0;
                        int.TryParse(smmcwcs, out icount);

                        int ishengy = idlsbcsxz - icount;
                        if (ishengy < 0)
                        {
                            ishengy = 0;
                        }
                        baocundlrj(com_yonghu.Text, "登录系统", "登录密码不正确", "失败");
                        MessageBox.Show(string.Format(@"登录密码不正确 还剩{0}次尝试机会", ishengy));
                        sql = string.Format(@" update USERE set MMCWCS='{0}'   where YHLB='{1}' ", icount + 1, com_yonghu.Text);
                        mquery.InsertDB(sql);

                        //终端锁定
                        if (idlsbcsxzzd < icount + 2)
                        {
                            //超出次数 写入安全日记

                         
                            //baocunaqrj("综端锁定", "查询", "业务系统", "否", "否", "成功", string.Format("终端登录密码错误超过限制:终端登录密码错误超过限制,锁定该终端"));//事件、类型（增、删、该、查）、模块、是否核心功能、是否非常规业务、结果和描述
                           // baocundlrj(com_yonghu.Text, "终端锁定", "终端登录密码错误超过限制,锁定该终端", "成功");
                            
                            //锁定帐号
                            MessageBox.Show("终端登录密码错误超过限制,该终端被锁定");
                            sql = string.Format(@"select * from  zongduan  where ZD_IP='{0}' ", sip);
                            if (mquery.selectDBcount(sql) > 0)
                            {
                                sql = string.Format(@" update zongduan set ZD_ZT='{0}'   where ZD_IP='{1}' ", "锁定", sip);
                            }
                            else
                            {
                                sql = string.Format(@"insert into zongduan(ZD_IP,ZD_ZT) values('{0}','{1}')", sip, "锁定");
                            }
                            mquery.InsertDB(sql);
                            savecaozuoriji(sql, "更新", "业务系统", "终端锁定");//保存操作日志， 操作类型，工况模块 内容
                        }
                        //终端锁定
                        if (ishengy < 1)
                        {
                            //超出次数 写入安全日记
                            //  baocunaqrj(com_yonghu.Text, "登录系统", "密码不正确");

                           // baocunaqrj(com_yonghu.Text, "用户登录密码错误超过限制", string.Format("用户登录密码错误超过限制,锁定该用户"));
                          //  baocunaqrj("用户登录", "查询", "业务系统", "否", "否", "失败", string.Format("用户登录密码错误超过限制:用户{0}登录密码错误超过限制,锁定该用户", com_yonghu.Text));//事件、类型（增、删、该、查）、模块、是否核心功能、是否非常规业务、结果和描述
                           // baocundlrj(com_yonghu.Text, "用户锁定", "用户登录密码错误超过限制,锁定该用户", "成功");
                            //锁定帐号
                            MessageBox.Show(string.Format("用户{0}登录密码错误超过限制,该用户被锁定", com_yonghu.Text));
                            sql = string.Format(@" update USERE set ZT='{0}',PASSWORD='{1}',QZXGMM='是'   where YHLB='{2}' ", "锁定", Encryption("admin_888888"), com_yonghu.Text);
                            //mquery.InsertDB(sql);
                            savecaozuoriji(sql, "更新", "业务系统", "用户锁定");//保存操作日志， 操作类型，工况模块 内容
                            this.Close();
                        }

                        return false;
                    }

                }
                else
                {
                    MessageBox.Show("不存在该用户名");
                    return false;
                }



            return true;
        }



        //创建 1个客户端套接字 和1个负责监听服务端请求的线程  
        Thread threadclient = null;
        Socket socketclient = null;
        public string decode(string text)
        {
            char[] words = text.ToCharArray();
            for (int i = 0; i < words.Length; i++)
            {
                int a = (int)words[i];
                if (a >= 48 && a <= 57)//数字0-9
                {
                    a = a - 3;
                    if (a < 48)
                        a = a + 10;
                }

                if (a >= 65 && a <= 90)//字母A-Z
                {
                    a = a - 3;
                    if (a < 65)
                        a = a + 26;
                }

                if (a >= 97 && a <= 122)//字母a-z
                {
                    a = a - 3;
                    if (a < 97)
                        a = a + 26;
                }
                words[i] = (char)(a);
            }
            return new string(words);
        }
        public void connet()
        {
            //定义一个套接字监听  
            socketclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //获取文本框中的IP地址  
            IPAddress address = IPAddress.Parse("127.0.0.1");

            //将获取的IP地址和端口号绑定在网络节点上  
            IPEndPoint point = new IPEndPoint(address, 8098);

            try
            {
                //客户端套接字连接到网络节点上，用的是Connect  
                socketclient.Connect(point);

            }
            catch (Exception)
            {
                Debug.WriteLine("连接失败\r\n");


                return;
            }

            threadclient = new Thread(recv);
            threadclient.IsBackground = true;
            threadclient.Start();
        }

        // 接收服务端发来信息的方法    
        void recv()
        {
            int x = 0;
            //持续监听服务端发来的消息 
            while (true)
            {
                try
                {
                    //定义一个1M的内存缓冲区，用于临时性存储接收到的消息  
                    byte[] arrRecvmsg = new byte[1024 * 1024];

                    //将客户端套接字接收到的数据存入内存缓冲区，并获取长度  
                    int length = socketclient.Receive(arrRecvmsg);
                    byte uSum1 = 0;
              
                    for (int kk = 0; kk < length-1; kk++)
                    {
                        uSum1 += (byte)(arrRecvmsg[kk]);
                    }
                    if (uSum1 == (byte)(arrRecvmsg[length - 1]))
                    {
                        //将套接字获取到的字符数组转换为人可以看懂的字符串  
                        string strRevMsg = Encoding.UTF8.GetString(arrRecvmsg, 0, length);

                        sjieshou = (strRevMsg);
                        bjieshou = true;
                    }
                    //if (x == 1)
                    //{

                    //    Debug.WriteLine("服务器:" + GetCurrentTime() + "\r\n" + strRevMsg + "\r\n\n");
                    //}
                    //else
                    //{

                    //    Debug.WriteLine(strRevMsg + "\r\n\n");
                    //    x = 1;
                    //}
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("远程服务器已经中断连接" + "\r\n\n");
                    Debug.WriteLine("远程服务器已经中断连接" + "\r\n");
                    break;
                }
            }
        }

        //发送字符信息到服务端的方法  
        void ClientSendMsg(string sendMsg)
        {
            //将输入的内容字符串转换为机器可以识别的字节数组     
            byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(sendMsg);
            int ileng = arrClientSendMsg.Length;
            ///增加校验发送
            byte[] buf= new byte[ileng + 1];
            byte uSum1 = 0;
            for (int kk = 0; kk < arrClientSendMsg.Length; kk++)
            {
                uSum1 += (byte)(arrClientSendMsg[kk]);
            }
            arrClientSendMsg.CopyTo(buf,0);
            buf[ileng] = uSum1;
            socketclient.Send(buf);
            //调用客户端套接字发送字节数组     
           // socketclient.Send(arrClientSendMsg);
            //将发送的信息追加到聊天内容文本框中     
          //  Debug.WriteLine("hello...." + ": " + GetCurrentTime() + "\r\n" + sendMsg + "\r\n\n");

        }
        //获取当前系统时间  
        DateTime GetCurrentTime()
        {
            DateTime currentTime = new DateTime();
            currentTime = DateTime.Now;
            return currentTime;
        }
       
        public void getip()
        {
           


            string name = Dns.GetHostName();
            IPAddress[] ipadrlist = Dns.GetHostAddresses(name);
            foreach (IPAddress ipa in ipadrlist)
            {
                if (ipa.AddressFamily == AddressFamily.InterNetwork)
                {
                    sip = ipa.ToString();
                   
                }
            }
        }
       

        private void button1_Click(object sender, EventArgs e)
        {
            setting f = new setting(com_yonghu.Text.Trim());
            f.ShowDialog();
        }


          private string Encryption(string express)//加密
        {
            CspParameters param = new CspParameters();
            param.KeyContainerName = "gzwk2006";
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param))
            {
                byte[] plaindate = Encoding.Default.GetBytes(express);
                byte[] encryptdate = rsa.Encrypt(plaindate, false);

                return Convert.ToBase64String(encryptdate);
            }
        }
        //
        private string Decrypt(string cip)//解密
        {
            CspParameters param = new CspParameters();
            param.KeyContainerName = "gzwk2006";
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param))
            {
                byte[] encryptdate = Convert.FromBase64String(cip);
                byte[] decryptdate = rsa.Decrypt(encryptdate, false);
                return Encoding.Default.GetString(decryptdate);
            }
        }

        public void updaterenshu()
        {
             Query mquery = new Query();
            string sql;
            sql = string.Format(@"Select * From dangqianzaixian  ");
            DataTable dt = mquery.GetTable(sql);
            if (dt.Rows.Count < 1)
            {
                sql = string.Format(@"insert into dangqianzaixian (dqzx_rs) values ('{0}')", "1");
            }
            else
            {
                int izzrs = 0;
                int.TryParse(dt.Rows[0]["dqzx_rs"].ToString().Trim(), out izzrs);
                sql = string.Format(@"update  dangqianzaixian set dqzx_rs='{0}' ", izzrs+1);
            }
            if (!mquery.UpdateTable(sql))
            {
                MessageBox.Show("添加失败");
            }
        }
        public void baocundlrj(string syonghuming,string dllx,string sfcg,string dljg)//登录日志 用户明 登录类型 是否成功
        {
             Query objquery = new Query();
            string ssql = "";

            ssql = string.Format(@"insert into dengluriji (username,dengluIP,dlqk,dlsj,dlsfcg,dljg) values 
                                    ('{0}',
                                    '{1}',
                                    '{2}',
                                    '{3}',
                                    '{4}',
                                    '{5}')", 
                                    syonghuming,
                                    sip,
                                    dllx,
                                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                    sfcg,
                                    dljg);
                if (!objquery.UpdateTable(ssql))
                {
                    MessageBox.Show("添加失败");
                }
        }
        ///编码
        public string EncodeBase64(string code_type, string code)
        {
            string encode = "";
            byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code);
            try
            {
                encode = Convert.ToBase64String(bytes);
            }
            catch
            {
                encode = code;
            }
            return encode;
        }
        ///解码
        public string DecodeBase64(string code_type, string code)
        {
            string decode = "";
            byte[] bytes = Convert.FromBase64String(code);
            try
            {
                decode = Encoding.GetEncoding(code_type).GetString(bytes);
            }
            catch
            {
                decode = code;
            }
            return decode;
        }
        public void savecaozuoriji(string sql, string sczlx, string sgnmk, string sneirong)//保存操作日志， 操作类型，工况模块 内容
        {

            string sneirongsql = EncodeBase64("utf-8", sql);
            sql = string.Format(@"insert into riji(RJ_YHXM,
                                                    RJ_DATE,
                                                    RJ_neirong,
                                                    RJ_IP,
                                                    RJ_CZLX,
                                                    RJ_CZJG,
                                                    RJ_GNKK,
                                                    RJ_CZTJ,
                                                    RJ_NRMS) values(
                                                    '{0}',
                                                    '{1}',
                                                    '{2}',
                                                    '{3}',
                                                    '{4}',
                                                    '{5}',
                                                    '{6}',
                                                    '{7}',
                                                    '{8}')",
                                                    com_yonghu.Text,
                                                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                                    sneirong,
                                                    sip,
                                                    sczlx,
                                                    "成功",
                                                    sgnmk,
                                                    "",
                                                    sneirongsql);
            Query objquery = new Query();
            objquery.UpdateTable(sql);
        }

        public void baocunshrj(string saqcl,string syonghuming, string srjnr)// 安全策略 用户名 日记内容
        {
            Query objquery = new Query();
            string ssql = "";

            ssql = string.Format(@"insert into shenjiriji (shrj_aqcl,shrj_yhdh,shrj_rjnr,shrj_sjsj) values 
                                    ('{0}',
                                    '{1}',
                                    '{2}',
                                    '{3}')",
                                    saqcl,
                                    syonghuming,
                                    srjnr,
                                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            if (!objquery.UpdateTable(ssql))
            {
                MessageBox.Show("添加失败");
            }
        }
        public void baocunaqrj(string shijian, string leixing, string mokuai, string hengxin, string feichanggui, string jieguo, string miaoshu)//事件、类型（增、删、该、查）、模块、是否核心功能、是否非常规业务、结果和描述
        {
            Query objquery = new Query();
            string ssql = "";
            ssql = string.Format(@"insert into anquanriji ([aqrj_yh]
                                      ,[aqrj_sj]
                                      ,[aqrj_yhip]
                                      ,[aqrj_yhlx]
                                      ,[aqrj_date]
                                      ,[aqrj_mokuai]
                                      ,[aqrj_sfhx]
                                      ,[aqrj_sffcg]
                                      ,[aqrj_jg]
                                      ,[aqrj_miaoshu]) values 
                                    ('{0}',
                                    '{1}',
                                    '{2}',
                                    '{3}',
                                    '{4}',
                                     '{5}',
                                     '{6}',
                                     '{7}',
                                     '{8}',
                                     '{9}')",
                                    com_yonghu.Text,
                                    shijian,
                                    sip,
                                    leixing,
                                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                    mokuai,
                                    hengxin,
                                    feichanggui,
                                    jieguo,
                                    Encryption(miaoshu));
            if (!objquery.UpdateTable(ssql))
            {
                MessageBox.Show("添加失败");
            }
        }
        public void baocunhxrj(string saqcl, string syonghuming, string srjnr)// 核心功能日记 用户名 日记内容
        {
            Query objquery = new Query();
            string ssql = "";
            ssql = string.Format(@"insert into hexinriji (shrj_aqcl,shrj_yhdh,shrj_yhip,shrj_rjnr,shrj_sjsj) values 
                                    ('{0}',
                                    '{1}',
                                    '{2}',
                                    '{3}')",
                                    saqcl,
                                    syonghuming,
                                    sip,
                                    Encryption(srjnr),
                                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            if (!objquery.UpdateTable(ssql))
            {
                MessageBox.Show("添加失败");
            }
        }
        public void baocunywczrj(string saqcl, string syonghuming, string srjnr)//业务操作日志 安全策略 用户名 日记内容
        {
            Query objquery = new Query();
            string ssql = "";
            ssql = string.Format(@"insert into yewucaozuoriji (shrj_aqcl,shrj_yhdh,shrj_rjnr,shrj_sjsj) values 
                                    ('{0}',
                                    '{1}',
                                    '{2}',
                                    '{3}')",
                                    saqcl,
                                    syonghuming,
                                    srjnr,
                                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            if (!objquery.UpdateTable(ssql))
            {
                MessageBox.Show("添加失败");
            }
        }
        public void baocunzysjrj(string saqcl, string syonghuming, string srjnr)//重要数据日志 安全策略 用户名 日记内容
        {
            Query objquery = new Query();
            string ssql = "";
            ssql = string.Format(@"insert into zhongyaoshujuriji (shrj_aqcl,shrj_yhdh,shrj_rjnr,shrj_sjsj) values 
                                    ('{0}',
                                    '{1}',
                                    '{2}',
                                    '{3}')",
                                    saqcl,
                                    syonghuming,
                                    srjnr,
                                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            if (!objquery.UpdateTable(ssql))
            {
                MessageBox.Show("添加失败");
            }
        }

        public void baocunaqsj(string saqcl, string syonghuming, string srjnr)//安全审计 安全策略 用户名 日记内容
        {
            Query objquery = new Query();
            string ssql = "";
            ssql = string.Format(@"insert into anquanshenjiriji (shrj_aqcl,shrj_yhdh,shrj_yhip,shrj_rjnr,shrj_sjsj) values 
                                    ('{0}',
                                    '{1}',
                                    '{2}',
                                    '{3}',
                                    '{4}')",
                                    saqcl,
                                    syonghuming,
                                    sip,
                                    Encryption(srjnr),
                                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            if (!objquery.UpdateTable(ssql))
            {
                MessageBox.Show("添加失败");
            }
        }
        private double DateDiff(DateTime DateTime1, DateTime DateTime2)
        {
            double dateDiff = 0;
            TimeSpan ts = DateTime1.Subtract(DateTime2).Duration();
            dateDiff = ts.Days;
            return dateDiff;
        }

        private void userlogin_Load(object sender, EventArgs e)
        {
            getip();
           

            //Query mquery = new Query();
            //string sql;
            //sql = string.Format(@"Select * From fzsz");

           
            //int.TryParse(mquery.GetDBString(sql, "tqtsts"), out itqtsts);
            //int.TryParse(mquery.GetDBString(sql, "dlsbcsxz"), out idlsbcsxz);
            //int.TryParse(mquery.GetDBString(sql, "zdsbcsxz"), out idlsbcsxzzd);


            //sql = string.Format(@"Select * From dangqianzaixian");

            //int.TryParse(mquery.GetDBString(sql, "dqzx_rs"), out izxrs);

            //sql = string.Format(@"Select * From ziyuankongzhi where username='1分钟访问次数超限' ");

            //int.TryParse(mquery.GetDBString(sql, "keyzhi"), out iyfzfwcs);
        }

        private void but_query_Click(object sender, EventArgs e)
        {

            if (com_yonghu.Text == "")
            {
                MessageBox.Show("用户名不能为空");
                com_yonghu.Focus();
            }
            else
            {
                if (t_mima.Text == "")
                {
                    MessageBox.Show("密码不能为空");
                    t_mima.Focus();
                }
                else
                {
                    //try
                    {
                        if (check())
                        {
                                MainForm m_obj = new MainForm("", sname, sip, syhjs);
                                this.Hide();
                                m_obj.ShowDialog();
                                this.Close();
                        }
                        else
                        {
                           

                            //Query mquery = new Query();
                            //string sql;
                            //sql = string.Format(@"Select * From Employee where EP_ID='{0}' and EP_PASS='{1}'", com_yonghu.Text, t_mima.Text);
                            //string sright = "0000000000";
                            //sright = mquery.GetDBString(sql, "EP_RIGHT");
                            //string sdly = mquery.GetDBString(sql, "EP_NAME");
                            //if (sright.Length > 0)
                            //{
                            //    MainForm m_obj = new MainForm("", sdly, sip, syhjs);
                            //    this.Hide();
                            //    m_obj.ShowDialog();
                            //    this.Close();


                            //}
                            //else
                            //{
                            //   // MessageBox.Show("账号或密码输入错误");
                            //    return;

                            //}
                        }

                    }
                }
            }
        }

        private void but_close_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}